import { FC, useCallback } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { observer, useLocalStore } from 'mobx-react';
import { Form, Input, Button } from 'antd';
import qs from 'qs';

import Icons from '@components/Icons';
import { userLoginApi } from '@services/service';
import { COMPLETELY_FILL_STYLE } from '@utils/config';
import { globalStore } from '@/stores/global';

const LoginForm: FC = () => {
  const global = useLocalStore(() => globalStore);
  const myStore = useLocalStore(() => ({
    logging: false
  }));

  const navigate = useNavigate();
  const location = useLocation();

  const handleLogin = useCallback((value: any) => {
    myStore.logging = true;
    userLoginApi({
      username: value.username,
      password: value.password
    })
      .then((res: any) => {
        if (res) {
          // 登录成功授权
          global.loginAuthorize();

          // 获取重定向地址
          const { redirectUrl } = qs.parse(location.search.substr(1));
          navigate((redirectUrl as string) || '/');
        }
      })
      .finally(() => {
        myStore.logging = false;
      });
  }, []);

  return (
    <>
      <Form
        name="rb-login"
        wrapperCol={{ offset: 3, span: 18 }}
        onFinish={handleLogin}
        autoComplete="off"
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: '请输入用户名'
            }
          ]}
        >
          <Input
            prefix={<Icons type="UserOutlined" style={{ color: 'rgb(24, 144, 255)' }} />}
            placeholder="用户名"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码'
            }
          ]}
        >
          <Input.Password
            prefix={<Icons type="LockOutlined" style={{ color: 'rgb(24, 144, 255)' }} />}
            placeholder="密码"
          />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 3, span: 18 }}>
          <Button
            type="primary"
            htmlType="submit"
            style={{ ...COMPLETELY_FILL_STYLE, height: '2.5rem' }}
            loading={myStore.logging}
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};

export default observer(LoginForm);
